import json
import requests
import base64
import getpass
from selenium import webdriver
from time import sleep
from datetime import datetime
from io import BytesIO
from PIL import Image
from sys import version_info

from selenium.webdriver.remote.webelement import WebElement

def wangke():
    #username = input("请输入账号：")
    username = '20199476'

    #password=getpass.getpass("请输入密码：")
    password='binglongwang000'

    name = input("请输入网课名字：")

    chrome_options = webdriver.ChromeOptions()
    # 使用headless无界面浏览器模式
    # chrome_options.add_argument("--proxy-server=http://218.75.158.153:3128")  # 代理ip
    chrome_options.add_argument('--headless')   # 增加无界面选项
    chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
    chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口大小, 窗口大小会有影响
    # 启动浏览器，获取网页源代码
    u = webdriver.Chrome(options=chrome_options)  # 地址为chromedriver.exe的地址

    url = "http://www.minghuaetc.com/user/login"
    u.get(url)
    # 等待5秒
    sleep(2)
    # 选择学校
    u.find_element_by_id('schoolId').click()
    u.find_element_by_xpath('//select/option[@value="15"]').click()  # value=15选的是中南林业科技大学涉外学院
    # 账号
    u.find_element_by_id('username').send_keys(username)
    # 密码
    u.find_element_by_id('password').send_keys(password)
    # 登录
    u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
    sleep(1)
    cookies = u.get_cookies()
    cookie = "token="+cookies[2]['value']
    # 停5秒等加载
    sleep(2)
    # 选择课程
    u.find_element_by_link_text(name).click()
    print("登录成功")

    # 停5秒等加载
    sleep(2)
    # 查询学习状态
    url = u.find_element_by_link_text("学习成绩").get_attribute('href')
    u.get(url)
    sleep(0.2)
    total_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]')
    print("已经学习 %s 个视频" % total_catalog.text)
    num = int(total_catalog.text)
    surplus_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]')
    print("尚未学习 %s 个视频" % surplus_catalog.text)
    u.find_element_by_id('state').click()
    u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
    u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
    sleep(0.5)
    flag = 0
    while 1:
        try:
            u.get(u.find_element_by_xpath('//*[@id="list"]/tbody/tr[1]/td[1]/a').get_attribute('href'))
        except:
            flag = 1
        try:
            if flag == 1:
                u.get(u.find_element_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a').get_attribute('href'))
        except:
            flag = 2
        try:
            if flag == 2:
                u.find_element_by_id('state').click()
                u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
                u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                sleep(0.5)
                u.get(u.find_element_by_xpath('//*[@id="list"]/tbody/tr[1]/td[1]/a').get_attribute('href'))
        except:
            flag = 3
        try:
            if flag == 3:
                u.find_element_by_id('state').click()
                u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
                u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                sleep(0.5)
                u.get(u.find_element_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a').get_attribute('href'))
        except:
            break

        # 播放
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]/canvas').click()
        sleep(5)
        try:
            yzm = u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/img[2]').get_attribute('src')
            #yzm = "http://www.minghuaetc.com/"+yzm

            download(yzm,cookie)
            img_path = "1.jpg"
            img = Image.open(img_path)
            result = base64_api(uname='yusheng615', pwd='1731249586', img=img)
            
            u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/input[2]').send_keys(result)
            u.find_element_by_link_text("开始播放").click()
        except:
            print("无验证码")
        # 静音
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[17]/canvas').click()
        print("开始时间是%s" % datetime.now())
        # 每个视频停留
        time = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[8]')
        time = str(time.text)
        sleep(int(time[8:10]) * 60 + 60)
        print("结束时间是%s" % datetime.now())
        u.get(url) #返回学习记录处
        sleep(0.2)
        total_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]')
        print("已经学习 %s 个视频" % total_catalog.text)
        num = int(total_catalog.text)
        surplus_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]')
        print("尚未学习 %s 个视频" % surplus_catalog.text)
        u.find_element_by_id('state').click()
        u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
        u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
        sleep(0.5)
            
    # 退出
    print("完成")
    u.quit()
    
def base64_api(uname, pwd,  img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""

    
def download(url, cookie):
    src = url

    header = {
        "Cookie": cookie,
    }

    r = requests.get(src, headers=header)

    with open('1.jpg', 'wb') as f:
        f.write(r.content)

    #print('下载完成')

    
if __name__ == "__main__":
    wangke()
    
    
